package com.kybs.kb_bytedance_attribution


import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import android.app.Activity
import android.content.Context
import com.bytedance.ads.convert.BDConvert
import com.bytedance.ads.convert.event.ConvertReportHelper

/** KbBytedanceAttributionPlugin */
class KbBytedanceAttributionPlugin: FlutterPlugin, MethodCallHandler, ActivityAware{
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private var applicationContext: Context? = null
  private var activity: Activity? = null // 可为空的 Activity 引用

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "kb_bytedance_attribution")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else if (call.method == "convertInit") {
      BDConvert.init(applicationContext!!, activity!!)
      result.success(null)
    } else if (call.method == "sendLaunchEvent") {
      BDConvert.sendLaunchEvent(applicationContext!!)
      result.success(null)
    } else if (call.method == "onEventV3") {
      ConvertReportHelper.onEventV3(call.argument("eventName")!!, call.argument("extraParams")!!)
      result.success(null)
    } else if (call.method == "onEventRegister") {
      ConvertReportHelper.onEventRegister(
        call.argument("registerMethod")!!,
        call.argument("isSuccess")!!
      );
      result.success(null)
    } else if (call.method == "onEventPurchase") {
      ConvertReportHelper.onEventPurchase(
        call.argument("contentType")!!,
        call.argument("contentName")!!,
        call.argument("contentId")!!,
        call.argument("contentNumber")!!,
        call.argument("paymentChannel")!!,
        call.argument("currency")!!,
        call.argument("isSuccess")!!,
        call.argument("currencyAmount")!!
      )
      result.success(null)
    }  else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    // 当 Activity 可用时调用，在此获取 Activity 引用
    this.activity = binding.getActivity()
  }

  override fun onDetachedFromActivityForConfigChanges() {
    // 当 Activity 因配置更改（如屏幕旋转）而被销毁时调用
    this.activity = null
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    // Activity 重新创建后调用
    this.activity = binding.getActivity()
  }

  override fun onDetachedFromActivity() {
    // Activity 被完全销毁时调用（例如用户按下返回键或系统杀死进程）
    this.activity = null // 释放 Activity 引用，防止内存泄漏
  }
}
